package com.wjbgn.electronicnian.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjbgn.electronicnian.convert.NianDoConvert;
import com.wjbgn.electronicnian.dto.NianDTO;
import com.wjbgn.electronicnian.dto.Result;
import com.wjbgn.electronicnian.entity.NianDO;
import com.wjbgn.electronicnian.entity.NianDumplingsDO;
import com.wjbgn.electronicnian.entity.NianUserDO;
import com.wjbgn.electronicnian.mapper.NianUserMapper;
import com.wjbgn.electronicnian.service.NianDumplingsService;
import com.wjbgn.electronicnian.service.NianService;
import com.wjbgn.electronicnian.service.NianUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * Description:
 * Create Date: 2022-01-20T11:06:12.883426600
 *
 * @author weirx
 * @version 1.0
 */
@Service
public class NianUserServiceImpl extends ServiceImpl<NianUserMapper, NianUserDO> implements NianUserService {

    @Autowired
    private NianService nianService;

    @Autowired
    private NianDumplingsService nianDumplingsService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result login(NianUserDO nianUserDO) {
        //查看用户是否存在
        NianUserDO one = this.getOne(new QueryWrapper<>(new NianUserDO(nianUserDO.getUsername())));
        if (ObjectUtils.isEmpty(one)) {
            // 新增用户
            this.save(nianUserDO);
            // 新用户要创建自己的老虎
            NianDO nian = nianService.createNian(nianUserDO.getId(), nianUserDO.getUsername());
            NianDTO nianDTO = NianDoConvert.doToDto(nian);
            // 获取饺子数量
            List<NianDumplingsDO> dumplings = nianDumplingsService.list(new QueryWrapper<>(new NianDumplingsDO(nian.getId())));
            int dumplingsNum = dumplings.stream().mapToInt(NianDumplingsDO::getDumplingsNum).sum();
            nianDTO.setDumplingsNum(dumplingsNum);
            return Result.success(nianDTO);
        } else {
            if (one.getPassword().equals(nianUserDO.getPassword())) {
                NianDO nian = nianService.getOne(new QueryWrapper<>(new NianDO(one.getId())));
                NianDTO nianDTO = NianDoConvert.doToDto(nian);
                List<NianDumplingsDO> dumplings = nianDumplingsService.list(new QueryWrapper<>(new NianDumplingsDO(nian.getId())));
                int dumplingsNum = dumplings.stream().mapToInt(NianDumplingsDO::getDumplingsNum).sum();
                nianDTO.setDumplingsNum(dumplingsNum);
                return Result.success(nianDTO);
            } else {
                return Result.failed("密码错误");
            }
        }
    }

}